from datetime import datetime

import requests
from bs4 import BeautifulSoup


def bins_for_bank(bank_name, country_abbr):
    cookies = {
        '_ga': 'GA1.1.479296914.1720401671',
        '_gcl_au': '1.1.1032536040.1720401688',
        '_clck': 'twbqhy%7C2%7Cfnc%7C0%7C1650',
        '__gads': 'ID=964377270d81dfdc:T=1720401670:RT=1720600443:S=ALNI_MafsA0w8NgPE7tBkjYnl9pmhj3pYA',
        '__gpi': 'UID=00000e8604216933:T=1720401670:RT=1720600443:S=ALNI_Mb53FjfZiuHahihoIjmI79dZukVCg',
        '__eoi': 'ID=1b11dd7476c0dc48:T=1720401670:RT=1720600443:S=AA-AfjZZvZ1USD1vHMtaccsoi2cV',
        '_ga_CGDE2TMKTW': 'GS1.1.1720599536.10.1.1720600659.60.0.0',
        'cfzs_google-analytics_v4': '%7B%22OFGW_pageviewCounter%22%3A%7B%22v%22%3A%2267%22%7D%7D',
        'cfz_google-analytics_v4': '%7B%22OFGW_engagementDuration%22%3A%7B%22v%22%3A%220%22%2C%22e%22%3A1752136658401'
                                   '%7D%2C%22OFGW_engagementStart%22%3A%7B%22v%22%3A%221720600658401%22%2C%22e%22'
                                   '%3A1752136658401%7D%2C%22OFGW_counter%22%3A%7B%22v%22%3A%22390%22%2C%22e%22'
                                   '%3A1752136658401%7D%2C%22OFGW_session_counter%22%3A%7B%22v%22%3A%2212%22%2C%22e'
                                   '%22%3A1752136658401%7D%2C%22OFGW_ga4%22%3A%7B%22v%22%3A%22fba09baf-bce5-4702-93ec'
                                   '-e6ba66292421%22%2C%22e%22%3A1752136658401%7D%2C%22OFGW__z_ga_audiences%22%3A%7B'
                                   '%22v%22%3A%22fba09baf-bce5-4702-93ec-e6ba66292421%22%2C%22e%22%3A1751937668785%7D'
                                   '%2C%22OFGW_let%22%3A%7B%22v%22%3A%221720600658401%22%2C%22e%22%3A1752136658401%7D'
                                   '%2C%22OFGW_ga4sid%22%3A%7B%22v%22%3A%223821135%22%2C%22e%22%3A1720602458401%7D%7D',
        'XSRF-TOKEN': 'eyJpdiI6IkYwTGc5T3VlVWJxVEJyWklzTzE4WUE9PSIsInZhbHVlIjoiaG83akpkRkdEMFRhVGVLT2RXbVRQYW1odzA4d1FaVXk4L2kvZkxtTlVmbWZySXlRQXVweGNCMWhmS2FxY0dOcGRrcUR1N3lHallFeFdsb3p5YlJreWl5cm9RVWxOREo4WEl6eWZSSlEwRXAzT0V2RXQ0YkNRZ3Y4c0sxeVJSZngiLCJtYWMiOiJjNjVlYmIzMTk2YTIwZGNkZjVjN2YxNGM2MDI2OWU3MWJjNGE1Y2ExY2VkNzQxNjk3YmY0ODM4N2MyZjhlNmVjIn0%3D',
        'bincheck_session': 'eyJpdiI6IkdGZVRKL2d1ZXI5dkdBY1hsZ3RxNFE9PSIsInZhbHVlIjoibGVrNUVxZ2tPVmFla2dnQ0MvR1FTNFMzOVJRNXpOdW10bTdZWTFYUXNSLzlXUW5yNGx4SWlJeStqMnYwOXVObVBXbjM1N0RtVVNSa09TSW5iZHo4bm9NMUJkblloc0M5T05QTU5FMGhwRTBJbXE4aE1WMDRxZzF2dTBKdEhHWmYiLCJtYWMiOiJhMWQzNjc3NDllMGZhY2E0Y2Y2NDc4YWNkYTA2YzUxMGNhMDBhMWJjZTQ2NDk3Mjc1MmQyYjJjYTM2NjZiNjM3In0%3D',
        'FCCDCF': '%5Bnull%2Cnull%2Cnull%2Cnull%2Cnull%2Cnull%2C%5B%5B13%2C%22%5B%5C%22DBABBg~BUoAAACA%5C%22%2C%5B'
                  '%5B8%2C%5B1720600658%2C860974000%5D%5D%5D%5D%22%5D%5D%5D',
        'FCNEC': '%5B%5B%22AKsRol876idHGX'
                 '-vkC3m5iY8u1uMLRBoCvUFNBLwkGxzXqn270XLkCZiWfq5YC5V2QKYIwEfpbmgpxlAweEYdvDMULjZtcfMhNSSwUej'
                 'GuHS7cSVr4XneQRcO11tgbH445gtEODC2qmomw35GlLwCEfN5glihVL6zg%3D%3D%22%5D%5D',
        '_clsk': '4c1a8q%7C1720600662340%7C10%7C1%7Cb.clarity.ms%2Fcollect',
    }

    headers = {
        'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,'
                  'application/signed-exchange;v=b3;q=0.7',
        'accept-language': 'en-US,en;q=0.9',
        'priority': 'u=0, i',
        'referer': 'https://bincheck.io/zh/af',
        'sec-ch-ua': '"Not/A)Brand";v="8", "Chromium";v="126", "Google Chrome";v="126"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"Windows"',
        'sec-fetch-dest': 'document',
        'sec-fetch-mode': 'navigate',
        'sec-fetch-site': 'same-origin',
        'sec-fetch-user': '?1',
        'upgrade-insecure-requests': '1',
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
                      'Chrome/126.0.0.0 Safari/537.36',
    }
    bank_name = bank_name.lower().replace(" ", "-")
    print(bank_name)
    response = requests.get(f'https://mail.bincheck.io/{country_abbr}/{bank_name}', cookies=cookies,
                            headers=headers)

    if response.status_code == 200:
        return response.status_code, response.text
    else:
        print(response.status_code, bank_name)
        return response.status_code, None


def bin_html_analysis(status, html, bank):
    """
    解析单个HTML,得到数据
    :param status:
    :param bank:
    :param html:
    :return:
    """
    if status != 200:
        print(bank)
        return status
    soup = BeautifulSoup(html, 'html.parser')
    organization = soup.find("div", class_="py-2 overflow-hidden").text
    trs = (
        soup.find_all("tr", class_="even:bg-opacity-50 even:bg-slate-50 dark:even:bg-opacity-10")
    )
    result_list = []
    for item in trs:
        tds = item.find_all("td")
        if tds is None or len(tds) == 0:
            continue
        bin_number = tds[0].find("a").text
        bin_number = bin_number.replace(" ↗", "")
        country = tds[1].find("a").text
        country = country.replace(" ↗", "")
        bank = tds[2].find("a").text

        card = tds[3].find("a").text
        card = card.replace(" ↗", "")
        card_type = tds[4].text
        card_type = card_type.replace("\n", "")
        card_level = tds[5].text
        card_level = card_level.replace("\n", "")
        organization = organization.replace("\n", "")

        json_item = {
            "organization": organization,
            "bin_number": bin_number,
            "country": country,
            "bank": bank.rstrip(),
            "card": card,
            "card_type": card_type,
            "card_level": card_level,
            "create_time": datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
            "update_time": datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
        }
        result_list.append(tuple(json_item.values()))
    return result_list


def get_crawler_bin_total(bankName, country_abbr):
    status, html = bins_for_bank(bankName, country_abbr)
    return bin_html_analysis(status, html, bankName)


if __name__ == '__main__':
    result = get_crawler_bin_total("UNION FIFTYFOUR, LTD.", "zm")
    print(result)
